package com.kx.game.center.manager;

import java.util.concurrent.*;


public class AsyncTaskManager {

    private static AsyncTaskManager instance = null;
    // 异步执行队列
    ExecutorService executor;
    // 异步定时队列
    ScheduledExecutorService scheduledExecutor;

    private AsyncTaskManager() {
        executor = Executors.newFixedThreadPool(3);
        scheduledExecutor = Executors.newScheduledThreadPool(3);
    }

    public static AsyncTaskManager getInstance() {
        if (instance == null) {
            synchronized (AsyncTaskManager.class) {
                if (instance == null) {
                    instance = new AsyncTaskManager();
                }
            }
        }
        return instance;
    }

    /**
     * 添加任务
     */
    public Future<?> addTask(Runnable task) {
        return executor.submit(task);
    }

    /**
     * 增加定时任务（毫秒为单位）（固定周期间隔）
     * 将在 initialDelay 后开始执行，
     * 然后在 initialDelay+period 后执行，
     * 接着在 initialDelay + 2 * period 后执行，
     * 依此类推。如果任务的任何一个执行遇到异常，则后续执行都会被取消
     *
     * @param timerTask
     * @param delay     延迟时间
     * @param period    周期时间(单位:豪秒)
     * @return
     */
    public ScheduledFuture<?> addTimerTaskWithFixedRate(Runnable timerTask, long delay, long period) {
        return scheduledExecutor.scheduleAtFixedRate(timerTask, delay, period, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止服务
     */
    public void shutDown() {
        executor.shutdownNow();
        scheduledExecutor.shutdownNow();
    }

}
